﻿using CNKI.TPI.Web.Admin.IBLL;
using CNKI.TPI.Web.Admin.IDAO;
using CNKI.TPI.Web.Base;
using CNKI.TPI.Web.Search.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Castle.DynamicProxy;
using CNKI.TPI.Web.Admin.Model;
using System.Data;
using CNKI.TPI.Web.Search.IDAO;
using System.Collections;
using System.Text.RegularExpressions;
namespace CNKI.TPI.Web.Admin.BLL
{
    public class UserMgmtService : BaseService, IUserMgmtService
    {
        private IUserDAO userDao = null;
        private IUserMgmtDAO userMDao = null;
        private IUserDBDAO userDBDAO = null;
        ICategoryDAO categoryDAO = null;

        public UserMgmtService(IUserMgmtDAO userMDao, IUserDBDAO userDBDAO, IUserDAO userDao, ICategoryDAO categoryDAO)
        {
            this.userDao = this.generator.CreateInterfaceProxyWithTarget<IUserDAO>(userDao, new IInterceptor[] { new LogInterceptor() });
            this.userMDao = this.generator.CreateInterfaceProxyWithTarget<IUserMgmtDAO>(userMDao, new IInterceptor[] { new LogInterceptor() });
            this.userDBDAO = this.generator.CreateInterfaceProxyWithTarget<IUserDBDAO>(userDBDAO, new IInterceptor[] { new LogInterceptor() });
            this.categoryDAO = this.generator.CreateInterfaceProxyWithTarget<ICategoryDAO>(categoryDAO, new IInterceptor[] { new LogInterceptor() });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IList<SYS_CMS_USER> GetUser(int pageIndex, int pageSize, out int count)
        {
            return userMDao.GetUserPageSize((pageIndex - 1) * pageSize, pageSize, out count);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IList<SYS_CMS_USER> GetUserByName(string userName, int pageIndex, int pageSize, out int count)
        {
            IList<SYS_CMS_USER> result = userMDao.GetUserByNamePageSize(userName, (pageIndex - 1) * pageSize, pageSize, out count);
            userDealRed(result);
            return result;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IList<SYS_CMS_GROUP> GetGroupByName(string groupName, int pageIndex, int pageSize, out int count)
        {
            IList<SYS_CMS_GROUP> result = userMDao.GetGroupByNamePageSize(groupName, (pageIndex - 1) * pageSize, pageSize, out count);
            if (result != null && result.Count > 0)
            {
                foreach (SYS_CMS_GROUP item in result)
                {
                    item.Name = ColumnAliasHelper.ChangeStr(item.Name);
                    item.Descript = ColumnAliasHelper.ChangeStr(item.Descript);
                    item.Name = StringHelper.ConvertHighlightFlag(item.Name);
                }
            }
            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="groupID"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IList<SYS_CMS_USER> GetUserByGroupID(int groupID, int pageIndex, int pageSize, out int count)
        {
            IList<SYS_CMS_USER> result = null;
            if (groupID == 0)//所有类型
            {
                result = userMDao.GetUserByNamePageSize("", (pageIndex - 1) * pageSize, pageSize, out count);
            }
            else
            {
                result = userMDao.GetUserByGroupPageSize(groupID, (pageIndex - 1) * pageSize, pageSize, out count);
            }

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="result"></param>
        private void userDealRed(IList<SYS_CMS_USER> result)
        {
            if (result != null && result.Count > 0)
            {
                foreach (SYS_CMS_USER item in result)
                {
                    item.Username = ColumnAliasHelper.ChangeStr(item.Username);
                    //命中词汇标红

                    if ((!String.IsNullOrEmpty(item.Username)) && item.Username.Contains("###") && item.Username.Contains("$$$"))
                    {
                        item.Username = StringHelper.ConvertHighlightFlag(item.Username);
                    }
                }
            }
        }

        /// <summary>
        /// 获取用户组
        /// </summary>
        /// <returns></returns>
        public IList<SYS_CMS_GROUP> GetGroup()
        {
            return userMDao.GetGroup();
        }

        /// <summary>
        /// 根据用户id获取用户IP
        /// </summary>
        /// <returns></returns>
        public IList<SYS_CMS_USER_IP> GetGroupIpByUserID(int userid)
        {
            IList<SYS_CMS_USER_IP> list=userMDao.GetGroupIpByUserID(userid);
            list = list.Where(c => c.Flag == 0).ToList();
            return list;

        }

        /// <summary>
        /// 根据用户租id获取用户组IP
        /// </summary>
        /// <returns></returns>
        public IList<SYS_CMS_USER_IP> GetGroupIpByGroupID(int gid)
        {
            IList<SYS_CMS_USER_IP> list = userMDao.GetGroupIpByUserID(gid);
            list = list.Where(c => c.Flag == 1).ToList();
            return list;

        }

        /// <summary>
        /// 删除对应的用户组
        /// </summary>
        /// <returns></returns>
        public bool DeleteUserGroup(string sysid)
        {
            bool result = userMDao.DeleteUserGroup(sysid);

            if (result)  //删除对应的用户租IP
            {
                if (sysid.IndexOf(',') >= 0) //多个用户组ID
                {
                    string[] str = sysid.Split(',');
                    foreach (string item in str)
                    {
                        int userid = int.Parse(item);
                        userMDao.DelGroupIPByGroupID(userid);
                    }
                }
                else
                {
                    int userid = int.Parse(sysid);
                    userMDao.DelGroupIPByGroupID(userid);
                }
            }
            return result;
        }

        /// <summary>
        /// 删除对应的ip段
        /// </summary>
        /// <returns></returns>
        public bool DeleteUserIP(string sysidstr)
        {
            return userMDao.DeleteUserIP(sysidstr);
        }

        /// <summary>
        /// 保存ip段，0更新，1插入
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="flage"></param>
        /// <returns></returns>
        public bool SaveUserIP(SYS_CMS_USER_IP obj, int flage)
        {
            if (flage == 0)
            {
                return userMDao.UpdateUserIp(obj);
            }
            else
            {
                return userMDao.InsertUserIp(obj);
            }
        }

        /// <summary>
        /// 获取单位名称
        /// </summary>
        /// <returns></returns>
        public IList<SYS_CMS_USER_UNIT> GetUnit()
        {
            return userMDao.GetUnit();
        }

        /// <summary>
        /// 获取部门
        /// </summary>
        /// <returns></returns>
        public IList<SYS_CMS_USER_UNIT_DEPT> GetDeptByUnitID(int uid)
        {
            return userMDao.GetDeptByUnitID(uid);
        }

        /// <summary>
        /// 判断用户名是否存在
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public int IsExitUser(string userName)
        {
            int m = 0;
            SYS_CMS_USER obj = userDao.GetUser(userName);
            if (obj != null)
            {
                m = 1;
            }
            return m;
        }

        /// <summary>
        /// 获取密级
        /// </summary>
        /// <returns></returns>
        public IList<SYS_CMS_SECURITY> GetSecurity()
        {
            return userDao.GetSecurityInfo();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="grouplist"></param>
        /// <param name="userid"></param>
        private void saveGroup(IList<SYS_CMS_USER_GROUP> grouplist, int userid)
        {
            if (grouplist != null && grouplist.Count > 0)
            {
                foreach (SYS_CMS_USER_GROUP item in grouplist)
                {
                    item.UserID = userid;
                    userMDao.InsertUserGroup(item);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="iplist"></param>
        /// <param name="userid"></param>
        private void saveIp(IList<SYS_CMS_USER_IP> iplist, int userid)
        {
            if (iplist != null && iplist.Count > 0)
            {
                foreach (SYS_CMS_USER_IP item in iplist)
                {
                    item.UrID = userid;
                    userMDao.InsertUserIp(item);
                }
            }
        }

        /// <summary>
        /// 保存用户相关信息
        /// </summary>
        /// <param name="userobj">用户</param>
        /// <param name="grouplist">用户组</param>
        /// <param name="iplist">用户IP</param>
        /// <param name="Flage">新增修改标识</param>
        /// <returns></returns>
        public int SaveUserInfo(SYS_CMS_USER userobj, IList<SYS_CMS_USER_GROUP> grouplist, IList<SYS_CMS_USER_IP> iplist)
        {
            int m = 0;
            try
            {
                if (userobj != null)
                {
                    bool f = false;
                    int userid = 0;
                    if (userobj.SysID == 0) //新增
                    {
                        f = userMDao.InsertUser(userobj);
                        if (f)
                        {
                            SYS_CMS_USER obj = userDao.GetUser(userobj.Username);//获取用户ID
                            userid = obj.SysID;
                            saveGroup(grouplist, userid);
                            saveIp(iplist, userid);
                            m = 1;
                        }
                    }
                    else //修改
                    {
                        f = userMDao.UpdateUser(userobj);
                        if (f)
                        {
                            userid = userobj.SysID;
                            //修改时先删除，在插入数据
                            userMDao.DelUserGroupByUserID(userid);
                            saveGroup(grouplist, userid);
                            userMDao.DelUserIPByUserID(userid);
                            saveIp(iplist, userid);
                            m = 1;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return m;
        }

        /// <summary>
        /// 删除对应的用户
        /// </summary>
        /// <returns></returns>
        public bool DeleteUser(string sysidstr)
        {
            bool result = userMDao.DeleteUser(sysidstr);
            if (result)  //删除对应的用户组 和用户ip
            {
                if (sysidstr.IndexOf(',') >= 0) //多个用户ID
                {
                    string[] str = sysidstr.Split(',');
                    foreach (string item in str)
                    {
                        int userid = int.Parse(item);
                        userMDao.DelUserGroupByUserID(userid);
                        userMDao.DelUserIPByUserID(userid);
                    }
                }
                else
                {
                    int userid = int.Parse(sysidstr);
                    userMDao.DelUserGroupByUserID(userid);
                    userMDao.DelUserIPByUserID(userid);
                }
            }

            return result;
        }

        /// <summary>
        /// 根据ID获取用户
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public SYS_CMS_USER GetUserInfoByID(int userid)
        {
            return userMDao.GetUserInfoByID(userid);
        }

        /// <summary>
        /// 根据用户ID获取用户对应得用户组（逗号分隔的用户组ID）
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public string GetUserGroupID(int userid)
        {
            string msd = "";
            try
            {
                IList<SYS_CMS_USER_GROUP> objlist = userMDao.GetUserGroup();
                IEnumerable<int> idstr = objlist.Where(c => c.UserID == userid).Select(c => c.GroupID).Distinct();
                msd = string.Join(",", idstr);
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return msd;
        }

        /// <summary>
        /// 保存用户组
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool SaveGroup(SYS_CMS_GROUP obj, IList<SYS_CMS_USER_IP> iplist)
        {
            bool m = false;
            if (obj.SysID == 0) //新增
            {
                m = userMDao.InsertGroup(obj);
                if (m)//新增成功后，增加IP表的数据
                {
                    IList<SYS_CMS_GROUP> list = userMDao.GetGroup();
                    int groupid = list.Where(c => c.Name == obj.Name).ToList()[0].SysID;
                    saveIp(iplist, groupid);
                }

            }
            else
            {
                m = userMDao.UpdateGroup(obj);
                if (m)
                {
                    userMDao.DelGroupIPByGroupID(obj.SysID);
                    saveIp(iplist, obj.SysID);
                }
            }
            return m;
        }

        /// <summary>
        /// 判断用户组是否存在
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public int IsExitUserGroup(string name, int sysid)
        {
            int m = 0;
            if (sysid == 0) //新增时判断
            {
                IList<SYS_CMS_GROUP> list = userMDao.GetGroup();
                if (list != null && list.Count > 0)
                {
                    if (list.Select(x => x.Name.ToUpper()).Contains(name.ToUpper()))
                    {
                        m = 1;
                    }
                }
            }
            else
            {  //修改时判断

                if (userMDao.IsExistUserGroupUpdate(name, sysid))
                {
                    m = 1;
                }

            }
            return m;
        }

        /// <summary>
        /// 删除密级
        /// </summary>
        /// <param name="sysidstr"></param>
        /// <returns></returns>
        public bool DeleteSecurity(string sysidstr)
        {
            return userMDao.DeleteSecurity(sysidstr);
        }

        /// <summary>
        /// 判断密级重复
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="sysid"></param>
        /// <returns>0:无重复，1名称重复，2值重复</returns>
        public int IsExitSecurity(string name, string value, int sysid)
        {
            int m = 0;
            if (sysid == 0) //新增时判断
            {
                IList<SYS_CMS_SECURITY> list = userDao.GetSecurityInfo();
                if (list != null && list.Count > 0)
                {
                    if (list.Select(x => x.Name).Contains(name))
                    {
                        m = 1;
                        return m;
                    }
                    if (list.Select(x => x.Value).Contains(value))
                    {
                        m = 2;
                        return m;
                    }
                }
            }
            else
            {  //修改时判断

                if (userMDao.IsExistSecurityName(name, sysid))
                {
                    m = 1;
                    return m;
                }
                if (userMDao.IsExistSecurityValue(value, sysid))
                {
                    m = 2;
                    return m;
                }

            }
            return m;
        }

        /// <summary>
        /// 保存密级
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool SaveSecurity(SYS_CMS_SECURITY obj)
        {
            if (obj.SysID == 0)
            {
                return userMDao.InsertSecurity(obj);
            }
            else
            {
                return userMDao.UpdateSecurity(obj);
            }
        }

        /// <summary>
        /// 获取用户单位  分页
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public IList<SYS_CMS_USER_UNIT> GetUnitPageSize(string unitname, int pageIndex, int pageSize, out int count)
        {
            IList<SYS_CMS_USER_UNIT> result = userMDao.GetUnitPageSize(unitname, (pageIndex - 1) * pageSize, pageSize, out count);
            if (result != null && result.Count > 0)
            {
                foreach (SYS_CMS_USER_UNIT item in result)
                {
                    item.unitname = ColumnAliasHelper.ChangeStr(item.unitname);
                    item.ADDRESS = ColumnAliasHelper.ChangeStr(item.ADDRESS);
                    item.CONTRACT = ColumnAliasHelper.ChangeStr(item.CONTRACT);
                    item.TELEPHONE = ColumnAliasHelper.ChangeStr(item.TELEPHONE);
                    item.unitname = StringHelper.ConvertHighlightFlag(item.unitname);
                }
            }
            return result;
        }

        /// <summary>
        /// 保存用户单位
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool SaveUnitInfo(SYS_CMS_USER_UNIT obj)
        {
            if (obj.SYSID == 0)
            {
                //获取下一个编码
                string unitcode = userMDao.GetNextUnitCode();
                obj.UNITCODE = unitcode;
                return userMDao.InsertUnit(obj);
            }
            else
            {
                return userMDao.UpdateUnit(obj);
            }
        }

        /// <summary>
        /// 删除用户单位
        /// </summary>
        /// <param name="sysidstr"></param>
        /// <returns></returns>
        public bool DeleteUnit(string sysidstr)
        {
            return userMDao.DeleteUnit(sysidstr);
        }

        /// <summary>
        /// 判断单位名称是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <param name="sysid"></param>
        /// <returns></returns>
        public int IsExitUnit(string name, int sysid)
        {
            int m = 0;
            if (sysid == 0) //新增时判断
            {
                IList<SYS_CMS_USER_UNIT> list = userMDao.GetUnit();
                if (list != null && list.Count > 0)
                {
                    if (list.Select(x => x.UNITNAME).Contains(name))
                    {
                        m = 1;
                    }
                }
            }
            else
            {  //修改时判断

                if (userMDao.IsExistUnitUpdate(name, sysid))
                {
                    m = 1;
                }

            }
            return m;
        }

        /// <summary>
        /// 获取单位下的部门节点
        /// </summary>
        /// <param name="unitid">单位id</param>
        /// <param name="garde">节点级别</param>
        /// <param name="code">父节点code  当code为空时，即获取根节点</param>
        /// <returns></returns>
        public IList<SYS_CMS_USER_UNIT_DEPT> GetDept(int unitid, int garde, string code)
        {
            IList<SYS_CMS_USER_UNIT_DEPT> list = userMDao.GetDept(unitid, garde, code);
            foreach (SYS_CMS_USER_UNIT_DEPT item in list)
            {
                item.SYSCODE = StringHelper.RemoveHighlightFlag(item.SYSCODE);
            }
            return list;
        }

        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="sysid"></param>
        /// <returns></returns>
        public bool DeleteDept(string sysid, string code, int unitid)
        {
            return userMDao.DeleteDept(sysid, code, unitid);
        }

        /// <summary>
        /// 判断部门名称是否重复
        /// </summary>
        /// <param name="name"></param>
        /// <param name="sysid"></param>
        /// <param name="unitid"></param>
        /// <returns></returns>
        public int IsExitDeptName(string name, int sysid, int unitid)
        {
            int m = 0;
            if (sysid == 0) //新增时判断
            {
                IList<SYS_CMS_USER_UNIT_DEPT> list = userMDao.GetDeptByUnitID(unitid);
                if (list != null && list.Count > 0)
                {
                    if (list.Select(x => x.DEPTNAME).Contains(name))
                    {
                        m = 1;
                    }
                }
            }
            else
            {  //修改时判断

                if (userMDao.IsExistDeptUpdate(name, sysid, unitid))
                {
                    m = 1;
                }

            }
            return m;
        }

        /// <summary>
        /// 保存部门
        /// </summary>
        /// <param name="unitid">单位ID</param>
        /// <param name="sysid">主键，新增时传0</param>
        /// <param name="deptname"></param>
        /// <param name="parentcode">父节点code</param>
        /// <param name="grade">当前节点的级别</param>
        /// <returns></returns>
        public bool SaveDeptInfo(int unitid, int sysid, string deptname, string parentcode, int grade)
        {
            if (sysid == 0)//增加
            {
                //获取下一个编码
                string dpcode = userMDao.GetNextDeptCode(unitid, parentcode, grade);
                SYS_CMS_USER_UNIT_DEPT obj = new SYS_CMS_USER_UNIT_DEPT();
                obj.UNITID = unitid;
                obj.DEPTNAME = deptname;
                obj.DEPTCODE = dpcode;
                obj.HASCHILDFLAG = 0;

                obj.GRADE = grade;
                obj.SORTNUM = int.Parse(dpcode);
                if (grade != 1) //下级节点，则需更新其父节点的 HASCHILDFLAG
                {
                    obj.SYSCODE = parentcode + dpcode;
                    userMDao.UpdateDeptChild(parentcode, unitid, 1);
                }
                else //一级节点
                {
                    obj.SYSCODE = dpcode;
                }
                return userMDao.InsertDept(obj);
            }
            else
            {
                return userMDao.UpdateDeptName(sysid, deptname);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public bool AddAllDBRight(int id, RightType rightType)
        {
            bool result = false;
            try
            {
                IList<SYS_CMS_DATABASE> dbList = userDBDAO.GetDatabaseList();
                foreach (SYS_CMS_DATABASE item in dbList)
                {
                    result = AddDBRight(id, item.SysID, rightType);
                    if (!result)
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dbID"></param>
        /// <returns></returns>
        public bool AddDBRight(int id, int dbID, RightType rightType)
        {
            bool result = false;
            try
            {
                SYS_CMS_USER_ACL_DB_RIGHT dbRight = null;
                dbRight = null;
                dbRight = userDao.GetDBRight(id, dbID, rightType);
                if (dbRight != null)
                {
                    BuildDBRight(dbRight, rightType);
                    result = userMDao.UpdateDBRight(dbRight);
                }
                else
                {
                    dbRight = new SYS_CMS_USER_ACL_DB_RIGHT();
                    BuildDBRight(dbRight, rightType);
                    dbRight.UrID = id;
                    dbRight.DBID = dbID;
                    result = userMDao.InsertDBRight(dbRight);
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dbID"></param>
        /// <returns></returns>
        public bool AddDBRight(int id, IList<int> dbID, RightType rightType)
        {
            bool result = false;
            try
            {
                foreach (int item in dbID)
                {
                    result = AddDBRight(id, item, rightType);
                    if (!result)
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dbRight"></param>
        /// <param name="rightType"></param>
        private void BuildDBRight(SYS_CMS_USER_ACL_DB_RIGHT dbRight, RightType rightType)
        {
            dbRight.DownloadCountOfDay = 0;
            dbRight.MaxDownloadCount = 0;
            dbRight.SecurityType = 0;
            dbRight.Flag = (int)rightType;
            dbRight.RightClsValue = "";
            dbRight.RightFieldName = "";
            dbRight.RightValue = -1;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public DataSet GetDBRightList(string id, int pageIndex, int pageSize, RightType rightType, string dbName, IList<SearchType> SearchTypeList = null)
        {
            DataSet result = InitDBRightDS();
            try
            {
                int count;
                IList<SYS_CMS_DATABASE> dbList = userDBDAO.GetDatabaseList(pageIndex, pageSize, out count, dbName, SearchTypeList);
                IList<SYS_CMS_USER_ACL_DB_RIGHT> rightList = userDao.GetDBRight(id, rightType);
                SYS_CMS_USER_ACL_DB_RIGHT dbRight = null;
                IList<SYS_CMS_USER_ACL_DB_RIGHT> tempList = null;
                //生成DBRightTable
                DataTable dt = result.Tables[0];
                DataRow dr = null;
                foreach (SYS_CMS_DATABASE dbInfo in dbList)
                {
                    dr = dt.NewRow();
                    tempList = rightList.Where(c => c.DBID == dbInfo.SysID).ToList();
                    if (tempList != null && tempList.Count > 0)
                    {
                        dbRight = tempList[0];
                    }
                    else
                    {
                        dbRight = null;
                    }

                    dr["ID"] = dbInfo.SysID;
                    dr["数据库名称"] = StringHelper.ConvertHighlightFlag(dbInfo.DatabaseName);
                    if (dbRight != null)
                    {

                        dr["每日下载量"] = dbRight.DownloadCountOfDay;
                        dr["最大下载量"] = dbRight.MaxDownloadCount;
                        dr["字段权限"] = dbRight.RightValue == -1 ? "所有字段" : dbRight.RightFieldName;
                        dr["导航权限"] = dbRight.RightValue == -1 ? "所有导航" : dbRight.RightClsValue;
                        dr["操作权限"] = SessionHelper.GetDBRightDesc(dbRight.RightValue);
                    }
                    dt.Rows.Add(dr);
                }
                //生成DBRight统计信息
                dt = result.Tables[1];
                dr = dt.NewRow();
                dr["TotalCount"] = count;
                dt.Rows.Add(dr);
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private DataSet InitDBRightDS()
        {
            DataSet result = new DataSet();
            DataTable dt = InitDBRightTable();
            result.Tables.Add(dt);
            dt = InitDBCountTable(dt);
            result.Tables.Add(dt);
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private DataTable InitDBCountTable(DataTable dt)
        {
            dt = new DataTable();
            dt.Columns.Add("TotalCount");
            return dt;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private DataTable InitDBRightTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("数据库名称");
            dt.Columns.Add("操作权限");
            dt.Columns.Add("每日下载量");
            dt.Columns.Add("最大下载量");
            dt.Columns.Add("字段权限");
            dt.Columns.Add("导航权限");

            return dt;
        }

        /// <summary>
        /// 保存用户对应得数据库权限
        /// </summary>
        /// <param name="authdblist">操作权限列表</param>
        /// <param name="fieldlist">字段权限列表</param>
        /// <param name="daycount">每天下载量</param>
        /// <param name="maxcount">最大下载量</param>
        /// <param name="dbid">数据库ID</param>
        /// <param name="userid">用户ID</param>
        /// <returns></returns>
        public bool AuthSaveUser(string authdblist, string fieldlist, int daycount, int maxcount, int dbid, int userid, RightType rightType, string navstr)
        {
            bool result = false;
            try
            {
                if (String.IsNullOrEmpty(authdblist))//没有操作权限时判断该数据是否存在，存在则删除数据，不存在则不用新增
                {
                    SYS_CMS_USER_ACL_DB_RIGHT dbr = null;
                    dbr = userDao.GetDBRight(userid, dbid, rightType);
                    if (dbr != null)
                    {
                        return userMDao.DelUserRight(userid, dbid, (int)rightType);
                    }
                    return true;
                }
                int authdbvalue = -1; //操作权限
                IList<SessionHelper.DBRightType> dbauthlist = new List<SessionHelper.DBRightType>();
                string[] str = authdblist.Split(',');
                foreach (string item in str)
                {
                    SessionHelper.DBRightType myEnum = (SessionHelper.DBRightType)Enum.Parse(typeof(SessionHelper.DBRightType), item, true);
                    dbauthlist.Add(myEnum);
                }//转枚举类型
                if (dbauthlist.Contains(SessionHelper.DBRightType.Manage))//管理权限
                {
                    fieldlist = "";
                    navstr = "";
                }
                else
                {
                    if (!dbauthlist.Contains(SessionHelper.DBRightType.Search))//如果没有包含检索权限，则把检索权限加上
                    {
                        dbauthlist.Add(SessionHelper.DBRightType.Search);
                    }
                    authdbvalue = (int)SessionHelper.BuildDBRight(dbauthlist);
                }

                SYS_CMS_USER_ACL_DB_RIGHT dbRight = null;
                dbRight = userDao.GetDBRight(userid, dbid, rightType);
                if (dbRight != null)
                {
                    AuthUserInfo(dbRight, fieldlist, authdbvalue, daycount, maxcount, (int)rightType, navstr);
                    dbRight.UrID = userid;
                    dbRight.DBID = dbid;
                    result = userMDao.UpdateDBRight(dbRight);
                }
                else
                {
                    dbRight = new SYS_CMS_USER_ACL_DB_RIGHT();
                    AuthUserInfo(dbRight, fieldlist, authdbvalue, daycount, maxcount, (int)rightType, navstr);
                    dbRight.UrID = userid;
                    dbRight.DBID = dbid;
                    result = userMDao.InsertDBRight(dbRight);
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }


        /// <summary>
        /// SYS_CMS_USER_ACL_DB_RIGHT  更新插入
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="dbID"></param>
        /// <param name="fieldlist"></param>
        /// <param name="authdbvalue"></param>
        /// <param name="clslist"></param>
        /// <param name="daycount"></param>
        /// <param name="maxcount"></param>
        /// <returns></returns>
        private void AuthUserInfo(SYS_CMS_USER_ACL_DB_RIGHT dbRight, string fieldlist, double authdbvalue, int daycount, int maxcount, int flage, string navstr)
        {
            dbRight.DownloadCountOfDay = daycount;
            dbRight.MaxDownloadCount = maxcount;
            dbRight.RightFieldName = fieldlist;
            dbRight.RightValue = (int)authdbvalue;
            dbRight.SecurityType = 0;
            dbRight.Flag = flage;
            dbRight.RightClsValue = navstr;
        }

        /// <summary>
        /// 获取用户权限数据
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="dbid"></param>
        /// <returns></returns>
        public SYS_CMS_USER_ACL_DB_RIGHT GetDBRight(int userid, int dbid, RightType rightType)
        {
            return userDao.GetDBRight(userid, dbid, rightType);
        }

        public DataTable GetDBCLS(int userId, int dbId, string dbCode, RightType rightType)
        {
            DataTable result = InitCLSTable();
            try
            {
                string oldcls = "";
                SYS_CMS_USER_ACL_DB_RIGHT userDBRight = userDao.GetDBRight(userId, dbId, rightType);
                if (userDBRight != null)
                {
                    oldcls = userDBRight.RightClsValue;
                }
                IList<CLS> clsList = categoryDAO.GetCategroyTypeAll(dbCode);
                DataRow dr = null;
                foreach (CLS item in clsList)
                {
                    dr = result.NewRow();
                    dr["id"] = item.SysID;
                    dr["name"] = item.Name;
                    dr["clsCode"] = "";
                    if (oldcls != "")
                    {
                        dr["clsCode"] = parserCLSInfo(oldcls, item.SysID);
                    }
                    result.Rows.Add(dr);
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        private DataTable InitCLSTable()
        {
            DataTable result = new DataTable();
            result.Columns.Add("id");
            result.Columns.Add("name");
            result.Columns.Add("clsCode");
            return result;
        }

        private string parserCLSInfo(string rightClsValue, int targetclsID)
        {
            string result = "";
            try
            {
                MatchCollection mc;
                Regex r = new Regex("[^|;].+?:\\d+((\\(.+?\\))|;|$)"); //定义一个Regex对象实例
                mc = r.Matches(rightClsValue);
                string clsID = null;
                string clsCode = null;
                string[] clsInfo = null;
                string cls = null;
                for (int i = 0; i < mc.Count; i++) //在输入字符串中找到所有匹配
                {
                    clsInfo = mc[i].Value.Split(':'); //将匹配的字符串添在字符串数组中
                    clsID = "";
                    clsCode = "";
                    if (clsInfo.Length > 1)
                    {
                        cls = clsInfo[1];
                        if (cls.Contains("("))
                        {
                            clsID = cls.Substring(0, cls.IndexOf('(')).TrimStart(';');
                            clsCode = cls.Substring(cls.IndexOf('(') + 1, cls.IndexOf(')') - cls.IndexOf('(') - 1);
                        }
                        else
                        {
                            clsID = cls.TrimEnd(';');
                        }
                    }

                    if (int.Parse(clsID) == targetclsID)
                    {
                        if ("".Equals(clsCode))
                        {
                            result = clsCode;
                            break;
                        }
                        else
                        {
                            result = result + "," + clsCode;
                        }
                    }
                }
                if (result != null && result.Length > 0)
                {
                    result = result.TrimStart(',');
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }
    }
}
